<?php

namespace app\admin\service;


use app\admin\model\User;
use think\Db;

/**
 * 报警中心-BI大屏-服务类
 * Class DeviceBindService
 * @package app\admin\service
 */
class PoliceCenterService extends BaseService
{
    public $schooleId;
    public $commonWhere;
    public $success;

    /**
     * 构造函数
     */
    public function __construct($schooleId=0, $userId = 0)
    {
        $userSchooleId = db('user')->where('id', $userId)->value('schoole_id');
        $this->schooleId = $schooleId ? $schooleId : ($userSchooleId ? $userSchooleId : 19);
        $this->commonWhere[] = ['schoole_id', '=', $this->schooleId];
        $this->success = [
            "msg" => '请求成功',
            "code" => 0
        ];
    }

    /**
     * 获取学校报警概况
     * @return void
     */
    public function getPoliceOverview()
    {
        // 报警类型
        $device_alarm_type_list = db('device_alarm_type')
            ->field('id,name')
            ->order('sort', 'asc')
            ->limit(4)
            ->whereNull('delete_time')
            ->select();
        // 学生ids
        $student_ids = db('student')
            ->where($this->commonWhere)
            ->where('status', 1)
            ->column('id');
        // 学生报警记录
        $student_resort_log = db('resort_log')
            ->field('id,da_type,status')
            ->whereIn('student_id', $student_ids)
            ->select();
        $tmp_resort_log = [];
        $tmp_resort_log_no = [];
        $resort_total_count = 0;
        $resort_total_count_no = 0;
        foreach ($student_resort_log as $item){
            if($item['status']){
                $resort_total_count++;
                if(isset($tmp_resort_log[$item['da_type']])){
                    $tmp_resort_log[$item['da_type']]['resort_count']++;
                }else{
                    $tmp_resort_log[$item['da_type']]['resort_count'] = 1;
                }
            }else{
                $resort_total_count_no++;
                if(isset($tmp_resort_log_no[$item['da_type']])){
                    $tmp_resort_log_no[$item['da_type']]['resort_count']++;
                }else{
                    $tmp_resort_log_no[$item['da_type']]['resort_count'] = 1;
                }
            }
        }
        $handle_list = [
            'total_count'=> $resort_total_count,
            'list'=> []
        ];
        $no_handle_list = [
            'total_count'=> $resort_total_count_no,
            'list'=> []
        ];
        foreach ($device_alarm_type_list as $k=>$item){
            $item['resort_count'] = isset($tmp_resort_log[$item['id']]['resort_count']) ? $tmp_resort_log[$item['id']]['resort_count'] : 0;
            $handle_list['list'][] = $item;
        }
        foreach ($device_alarm_type_list as $k=>$item){
            $item['resort_count'] = isset($tmp_resort_log_no[$item['id']]['resort_count']) ? $tmp_resort_log_no[$item['id']]['resort_count'] : 0;
            $no_handle_list['list'][] = $item;
        }
        $this->success['data'] = [
            'handle'=> $handle_list,
            'no_handle'=> $no_handle_list
        ];

        return $this->success;
    }

    /**
     * 今日各年级未处理报警统计
     * @return array
     */
    public function getTodayUntreatedTotal()
    {
        $grade_list = db('grade')
            ->field('id,title,grade_key')
            ->where($this->commonWhere)
            ->where('mark', 1)
            ->order('sort', 'asc')
            ->select();
        foreach ($grade_list as $k=>$item){
            // 年级今日未处理报警
            $student_ids = db('student')
                ->where(['grade_id'=> $item['grade_key'],'schoole_id'=>$this->schooleId,'mark'=>1])
                ->column('id');
            $untreated_count = db('resort_log')
                ->whereIn('student_id', $student_ids)
                ->where('status', 0)
                ->whereTime('belong_time', 'd')
                ->count();
            $grade_list[$k]['untreated_count'] = $untreated_count;
        }
        $this->success['data'] = $grade_list;

        return $this->success;
    }

    /**
     * 当日各年级报警数量分布
     * @return array
     */
    public function getTodayResortTotal()
    {
        $grade_list = db('grade')
            ->field('id,title,grade_key')
            ->where($this->commonWhere)
            ->where('mark', 1)
            ->order('sort', 'asc')
            ->select();
        // 当日学生报警信息
     /*   $student_resort_list = db('resort_log')
            ->alias('r')
            ->field('r.id,r.da_type,r.student_id,s.grade_id')
            ->where(['s.status'=> 1, 's.schoole_id'=> $this->schooleId])
            ->whereTime('r.belong_time', 'd')
            ->join('student s', 's.id = r.student_id', 'left')
            ->select();*/
        //$tmp_resort_list = [];
        //print_r($student_resort_list);die();
       /* foreach ($student_resort_list as $item){
            if(isset($tmp_resort_list[$item['grade_id']]) && isset($item['resort_total_list'])){
                if(isset($tmp_resort_list[$item['grade_id']][$item['resort_total_list']])){
                    if(isset($tmp_resort_list[$item['grade_id']]['resort_total_list'][$item['da_type']])){
                        $tmp_resort_list[$item['grade_id']]['resort_total_list'][$item['da_type']]['count']++;
                    }else{
                        $tmp_resort_list[$item['grade_id']]['resort_total_list'][$item['da_type']]['count'] = 1;
                    }
                }else{
                    $tmp_resort_list[$item['grade_id']]['resort_total_list'][$item['da_type']]['count'] = 1;
                }
            }else{
                $tmp_resort_list[$item['grade_id']]['resort_total_list'][$item['da_type']]['count'] = 1;
            }
        }*/
        $device_alarm_type_list = db('device_alarm_type')
            ->field('id,name')
            ->order('sort', 'asc')
            ->whereNull('delete_time')
            ->select();
        $tmp_total_list = [];
        foreach ($grade_list as $k=>$item){
            $tmp_total_resort_count = 0;
            $ids = Db::table('think_student')->field('id')
                ->where('mark',1)
                ->where('schoole_id',$this->schooleId)
                ->where('grade_id',$item['grade_key'])
                ->column('id');
            foreach ($device_alarm_type_list as $value){
                // 年级今日报警
                //$resort_count = isset($tmp_resort_list[$item['id']]['resort_total_list'][$value['id']]['count']) ?
                //    $tmp_resort_list[$item['id']]['resort_total_list'][$value['id']]['count'] : 0;
                $resort_count = db('resort_log')
                    ->where('da_type',$value['id'])
                    ->whereIn('student_id',$ids)
                    ->whereTime('belong_time', 'd')
                    ->count();
                $grade_list[$k]['resort_list'][] = [
                    'resort_name'=> $value['name'],
                    'resort_count'=> $resort_count
                ];
                $tmp_total_resort_count += $resort_count;
            }
            $tmp_total_list[] = [
                'id'=> $item['id'],
                'title'=> $item['title'],
                'resort_count'=> $tmp_total_resort_count
            ];
        }

        $this->success['data'] = [
            'total_list'=> $tmp_total_list,
            'detail_list'=> $grade_list
        ];

        return $this->success;
    }

    /**
     * 获取各年级报警趋势
     * @return array
     */
    public function getGradeResortTrend()
    {
        $grade_list = db('grade')
            ->field('id,title,grade_key')
            ->where($this->commonWhere)
            ->where('mark', 1)
            ->order('sort', 'asc')
            ->select();
        $student_list = db('student')
            ->field('id,grade_id')
            ->where($this->commonWhere)
            ->where('status', 1)
            ->select();
        $student_ids = [];
        foreach ($student_list as $item){
            if(isset($student_ids[$item['grade_id']])){
                array_push($student_ids[$item['grade_id']], $item['id']);
            }else{
                $student_ids[$item['grade_id']] = [$item['id']];
            }
        }

        foreach ($grade_list as $k=>$item){
            $tmp_student_ids = isset($student_ids[$item['grade_key']]) ? $student_ids[$item['grade_key']] : [];
            $grade_list[$k]['resort_count_week'] = $this->getResortTotal($tmp_student_ids, 'week');
            $grade_list[$k]['resort_count_month'] = $this->getResortTotal($tmp_student_ids, 'month');
            $grade_list[$k]['resort_count_year'] = $this->getResortTotal($tmp_student_ids, 'year');
        }

        $this->success['data'] = $grade_list;

        return $this->success;
    }

    /**
     * 获取当日各年级报警处理率
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTodayResortHandle()
    {
        $grade_list = db('grade')
            ->field('id,title,grade_key')
            ->where($this->commonWhere)
            ->where('mark', 1)
            ->order('sort', 'asc')
            ->select();
    /*    $student_list = db('student')
            ->field('id,grade_id')
            ->where($this->commonWhere)
            ->where('status', 1)
            ->select();
        $student_ids = [];
        foreach ($student_list as $item){
            if(isset($student_ids[$item['grade_id']])){
                array_push($student_ids[$item['grade_id']], $item['id']);
            }else{
                $student_ids[$item['grade_id']] = [$item['id']];
            }
        }*/
        foreach ($grade_list as $k=>$item){
            //$tmp_student_ids = isset($student_ids[$item['grade_key']]) ? $student_ids[$item['grade_key']] : [];
            $tmp_student_ids = Db::table('think_student')
                ->where('schoole_id',$this->schooleId)
                ->where('grade_id',$item['grade_key'])
                ->where('mark',1)
                ->column('id');
            $resort_count_day = $this->getResortTotal($tmp_student_ids, 'd');
            $resort_count_handle = $this->getResortTotal($tmp_student_ids, 'd', 1);
            $a = $resort_count_day ? round($resort_count_handle / $resort_count_day * 100) : '0';
            $grade_list[$k]['resort_handle_rate'] = (string)$a;
            //$grade_list[$k]['resort_handle_rate'] = '0';
        }
        $this->success['data'] = $grade_list;

        return $this->success;
    }

    /**
     * 获取今日报警概况
     * @return void
     */
    public function getTodayResortOverview()
    {

        $resort_count = $this->getResortTotalDay(1);
        $resort_handle_count = $this->getResortTotalDay(2);
        $resort_untreated_count = $this->getResortTotalDay(3);

        $this->success['data'] = [
            'resort_count'=> $resort_count,
            'resort_handle_count'=> $resort_handle_count,
            'resort_untreated_count'=> $resort_untreated_count,
            'resort_handle_rate'=> $resort_count ? round($resort_handle_count / $resort_count * 100).'%' : '0%'
        ];

        return $this->success;
    }

    /**
     * 获取今日报警列表
     * @return null
     */
    public function getTodayResortList($page, $page_size)
    {
        $list = db('resort_log')
            ->alias('r')
            ->field('r.id,r.imei,da.name as content,r.remark,r.create_time,s.name student_name,g.title grade_name,c.title class_name')
            ->join('student s', 's.id = r.student_id and s.mark =1', 'left')
            ->join('grade g', 'g.grade_key = s.grade_id', 'left')
            ->join('class c', 'c.class_key = s.class_id', 'left')
            ->join('device_alarm_type da', 'da.id = r.da_type and da.delete_time IS NULL')
            ->where('r.schoole_id',$this->schooleId)
            //->whereTime('r.create_time', 'd')
            ->paginate($page_size)
            ->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });

        $this->success['data'] = [
            'total'=> $list->total(),
            'list'=> $list->items()
        ];

        return $this->success;
    }

    /**
     * 报警数量统计
     * @param $student_ids
     * @param $type
     * @param $status
     * @return void
     */
    private function getResortTotal($student_ids=[], $type= 'month', $status='')
    {

        switch ($type){
            case 'week':
                $belong_time_op = 'w';
                break;
            case 'month':
                $belong_time_op = 'm';
                break;
            case 'year':
                $belong_time_op = 'y';
                break;
            default:
                $belong_time_op = 'd';
                break ;
        }
        $resort_count = db('resort_log')
            ->whereIn('student_id', $student_ids)
            ->whereTime('belong_time', $belong_time_op)
            ->where(function($query) use ($status){
                if($status != ''){
                    $query->where('status', $status);
                }
            })
            ->count('id');
        return $resort_count;
    }

    private function getResortTotalDay($status='')
    {
        $grade_list = db('grade')
            ->field('id,title,grade_key')
            ->where($this->commonWhere)
            ->where('mark', 1)
            ->order('sort', 'asc')
            ->select();
        $student_ids = db('student')
            ->where(['mark'=>1])
            ->where('schoole_id',$this->schooleId)
            ->where('grade_id','in',array_column($grade_list,'grade_key'))
            ->column('id');

        $t1 = strtotime(date('Y-m-d'));
        $t2 = strtotime(date('Y-m-d 23:59'));
        if($status == 1){
            $resort_count = db('resort_log')
                ->whereIn('student_id', $student_ids)
                //->whereTime('belong_time', 'd')
                ->where('belong_time', ['>',$t1],['<',$t2])
                ->count();
        }else{
            if($status == 2){
                $status = '1';
            }
            if($status == 3){
                $status = '0';
            }
            $resort_count = db('resort_log')
                ->whereIn('student_id', $student_ids)
                ->where('status',$status)
                ->where('belong_time', ['>',$t1],['<',$t2])
                ->count();
        }

        return $resort_count;
    }
}

